package com.xiaoyu.lanling.feature.board.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.event.board.RichCheckedChangeEvent
import com.xiaoyu.lanling.view.OnShowFragment
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class RichWrapperFragment : OnShowFragment() {

    private val fragmentList = mutableListOf<OnShowFragment>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_rich_board_wrapper, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        initView()
        initEvent()
    }

    private fun initView() {
        val weekBoardFragment = RichWeekBoardFragment()
        val sumBoardFragment = RichSummedBoardFragment()

        fragmentList.add(weekBoardFragment)
        fragmentList.add(sumBoardFragment)

        initFragmentStatus()
        showFragment(0)
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onCheckedChanged(event: RichCheckedChangeEvent) {
                showFragment(event.checkedIndex)
            }
        })
    }

    private fun initFragmentStatus() {
        for (fragment in fragmentList) {
            childFragmentManager.beginTransaction()
                    .add(R.id.board_wrapper, fragment)
                    .commit()

            childFragmentManager.beginTransaction()
                    .hide(fragment)
                    .commit()
        }
    }

    private fun showFragment(index: Int) {
        for ((i, fragment) in fragmentList.withIndex()) {
            if (i == index) {
                childFragmentManager.beginTransaction()
                        .show(fragment)
                        .commit()
            } else {
                childFragmentManager.beginTransaction()
                        .hide(fragment)
                        .commit()
            }
        }
    }
}